package com.movieticket.controller;

import com.movieticket.dto.OrderDTO;
import com.movieticket.model.entity.Order;
import com.movieticket.model.entity.User;
import com.movieticket.repository.OrderRepository;
import com.movieticket.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.Authentication;

import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/orders")
@CrossOrigin(origins = "*")
public class OrderController {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private UserRepository userRepository;

    @PostMapping
    public ResponseEntity<Order> createOrder(@RequestBody OrderDTO orderDTO) {
        System.out.println("Received OrderDTO: " + orderDTO.toString());
        System.out.println("Payment Method from DTO: " + orderDTO.getPaymentMethod());
        try {
            Order order = new Order();
            order.setOrderNumber(orderDTO.getOrderNumber());
            order.setMovieTitle(orderDTO.getMovieTitle());
            order.setCinemaName(orderDTO.getCinemaName());
            order.setHallName(orderDTO.getHallName());

            if (orderDTO.getShowtime() != null && !orderDTO.getShowtime().isEmpty()) {
                order.setShowtime(LocalDateTime.parse(orderDTO.getShowtime(), java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")));
            }

            order.setSeats(orderDTO.getSeats());
            order.setQuantity(orderDTO.getQuantity());
            order.setTicketPrice(orderDTO.getTicketPrice());
            order.setServiceFee(orderDTO.getServiceFee());
            order.setTotalPrice(orderDTO.getTotalPrice());
            order.setPaymentMethod(orderDTO.getPaymentMethod());
            order.setStatus("PAID");

            if (orderDTO.getUserId() == null) {
                System.err.println("Error: userId is null in OrderDTO");
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST); // User ID is required
            }
            Optional<User> userOptional = userRepository.findById(orderDTO.getUserId());
            if (userOptional.isEmpty()) {
                System.err.println("Error: User not found for userId: " + orderDTO.getUserId());
                return new ResponseEntity<>(HttpStatus.NOT_FOUND); // User not found
            }
            order.setUser(userOptional.get());

            order.setCreatedAt(LocalDateTime.now());

            Order savedOrder = orderRepository.save(order);
            System.out.println("Order saved successfully: " + savedOrder.getId());
            return new ResponseEntity<>(savedOrder, HttpStatus.CREATED);
        } catch (DateTimeParseException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Order>> getUserOrders(@PathVariable Long userId) {
        try {
            List<Order> orders = orderRepository.findByUserIdOrderByCreatedAtDesc(userId);
            return new ResponseEntity<>(orders, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @DeleteMapping("/{orderId}")
    public ResponseEntity<Void> deleteOrder(@PathVariable Long orderId, Authentication authentication) {
        Order order = orderRepository.findById(orderId).orElse(null);
        if (order == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        // 获取当前登录用户名
        String currentUsername = authentication.getName();
        // 只允许订单拥有者或管理员删除
        boolean isOwner = order.getUser().getUsername().equals(currentUsername);
        boolean isAdmin = authentication.getAuthorities().stream()
            .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));
        if (!isOwner && !isAdmin) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        orderRepository.deleteById(orderId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
} 